package com.cskaoyan.aspect;

import com.cskaoyan.bean.Log;
import com.cskaoyan.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author stone
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    LogService logService;

    @Pointcut("@annotation(com.cskaoyan.annotation.ExecutionLog)")
    public void methodPointcut(){}

    @Around("methodPointcut()")
    public Object executeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object target = joinPoint.getTarget();
        if (target instanceof LogService) {
            return joinPoint.proceed();
        }
        String simpleName = joinPoint.getTarget().getClass().getSimpleName();// 类名
        String name = joinPoint.getSignature().getName();//方法名
        String operation = simpleName + "." + name;
        Boolean success = true;
        String errMsg = null;
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            success = false;
            errMsg = throwable.getMessage();
            throwable.printStackTrace();
        } finally {
            Log log = new Log(null, operation, new Date(), success, errMsg);
            logService.createLog(log);
        }
        return proceed;

    }
}
